//
// Author: Vladimir Migashko <migashko@gmail.com>, (C) 2011
//
// Copyright: See COPYING file that comes with this distribution
//

#ifndef FASYS_LIBS_CHANNEL_SERVICE_CHANNEL_CONNECTION_HPP
#define FASYS_LIBS_CHANNEL_SERVICE_CHANNEL_CONNECTION_HPP

#include <fas/inet/connection.hpp>
#include "channels/messages_channels.hpp"
#include "ichannel_server.hpp"

namespace fasys{ namespace service{ namespace channel{

namespace ai = ::fas::inet;

template<typename A, typename F>
class connection
 : public ai::mux_connection_base<A, F>
{
  // typedef ::fasys::channels::channel_id_t channel_id_t;
  typedef ai::mux_connection_base<A, F> super;
  typedef std::set<channel_id_t> subscribe_channels;
  subscribe_channels _channel_ids;
public:
  ::fasys::channels::messages_channels* channels;

  template<typename T>
  bool _release(T& t)
  {
    std::cout << "_release"<< std::endl;
    _channel_ids.clear();
    return super::_release(t);
  }

  ichannel_server* server;

  connection()
    : channels(0)
    , server(0){}

  void incoming(message_publish& mp)
  {
    std::cout << "void incoming(message_publish& mp)"<< std::endl;
    message_notify mn;
    
    if ( channels )
    {
      if ( channels->publish(mp, mn) )
      {
        if (server)
        {
          std::cout << "incoming message"<< std::endl;
          server->process(mn);
        }
      }
      else
      {
      }
    }
  }

  void incoming( subscribe_request& srq )
  {
    std::cout << "subscribe_request "<< srq.timeout << std::endl;
    subscribe_response srs;
    //channel_id_t id = channels->subscribe(s.channel, s.timeout);
    channels->subscribe(srq, srs);
    if (srs.channel_id > 0)
      _channel_ids.insert(srs.channel_id);
    super::get_aspect().template get<_subscribe_>().notify(*this, srs);
    // std::cout << "subscribe " << id << std::endl;
  }

  void outgoing(const message_notify& cmd)
  {
    std::cout << "outgoing message 1"<< std::endl;
    super::get_aspect().template get<_message_>().notify(*this, cmd);
    std::cout << "outgoing message 2"<< std::endl;
  }

};

}}}

#endif
